<template>
  <div>
    <template v-if="user">
      <span style="cursor:default">欢迎您，</span>
      <span class="user">{{ user.name }}</span>
      [
      <span @click="logout" class="exit">退出</span>]
    </template>
    <template v-else>
      <nuxt-link to="/login" class="login">立即登录</nuxt-link>
      <nuxt-link class="register" to="/register">注册</nuxt-link>
    </template>
  </div>
</template>
<script>
import * as homeApi from "@/server/home.js";
export default {
  data() {
    return {
      user: null
    };
  },
  methods: {
    isLogin: function() {
      var userId = localStorage.getItem("user");
      if (userId == null) {
        userId = 0;
      }
      homeApi.getUser(userId).then(result => {
        if (result.data.code == 200) {
          this.user = result.data.data;
        } else if (result.data.code == 202) {
          localStorage.removeItem("user");
          this.$message({
            message: result.data.message,
            type: "warning"
          });
          setTimeout(() => {
            this.$router.push("/login");
          }, 1000);
        }
      });
    },
    logout: function() {
      var userId = localStorage.getItem("user");
      if (userId == null) {
        userId = 0;
      } else {
        homeApi.logout(userId).then(result => {
          localStorage.removeItem("user");
          this.$message({
            message: "注销成功！",
            type: "success"
          });
          this.$router.push({ path: "/login" });
        });
      }
    }
  },
  mounted() {
    this.isLogin();
  }
};
</script>
<style>
.user {
  color: #31bbac;
  cursor: default;
}
.exit {
  color: #31bbac;
  cursor: pointer;
}
</style>